package com.cykj.pos.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cykj.common.core.controller.BaseController;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.utils.Base64Util;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.BizMerchantReceiverDTO;
import com.cykj.pos.domain.dto.ayg.ApiBaseResult;
import com.cykj.pos.domain.vo.ApiayfParam;
import com.cykj.pos.service.IBizMerchantReceiverService;
import com.cykj.pos.service.IBizMerchantService;
import com.cykj.pos.service.IBizMicroInfoService;
import com.cykj.pos.service.IBizWithdrawalRecordsService;
import com.cykj.pos.service.impl.BizWithdrawalRecordsServiceImpl;
import com.cykj.pos.util.OrderUtil;
import com.cykj.pos.util.ayfUtil.HttpCallUtil;
import com.cykj.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author 许晓龙
 * @date 2025/4/2 11:16
 * 安易发代付
 */

@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/anyifa")
public class BizMerchantAnYiFaDaiFuController extends BaseController {

    private final IBizMerchantService bizMerchantService;

    private final IBizMicroInfoService bizMicroInfoService;

    private final IBizMerchantReceiverService iBizMerchantReceiverService;

    private final IBizWithdrawalRecordsService iBizWithdrawalRecordsService;

    private final BizWithdrawalRecordsServiceImpl bizWithdrawalRecordsServiceImpl;

    private final ISysUserService iSysUserService;

    @Value("${ayf.signingUrl}")
    private String signingUrl;

    @Value("${ayf.disbursementUrl}")
    private String disbursementUrl;
    @Value("${ayf.callbackUrl}")
    private String callbackUrl;


    @ApiOperation("安易发商户下发收款者签约")
    @PostMapping("/withReceiverNews")
    public AjaxResult withdrawalReceiverNews(@RequestBody BizMerchantReceiver bizMerchantReceiver) {
        System.out.println("--------------------------");
        System.out.println("---------签约增加商户下发收款者-----------------");
        System.out.println("--------------------------");
        AjaxResult ajaxResult = AjaxResult.success("增加商户下发收款者");

        String merchId = bizMerchantService.selectMerchId(bizMerchantReceiver.getUserId().toString());
        bizMerchantReceiver.setMerchId(Long.parseLong(merchId));
        BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(Long.parseLong(merchId));
        if(bizMicroInfoByMerchId == null){
            return AjaxResult.error("未实名认证");
        }
        BizMerchantReceiverDTO bizMerchantReceiverDTO = new BizMerchantReceiverDTO();
        bizMerchantReceiverDTO.setMerchId(bizMicroInfoByMerchId.getMerchId());
        bizMerchantReceiverDTO.setUserId(bizMerchantReceiver.getUserId());
        //先查询商户下发收款者是否存在
        BizMerchantReceiver bizMerchantReceiver1 = iBizMerchantReceiverService.bizMerchantReceiver(bizMerchantReceiverDTO);
        if (bizMerchantReceiver1 != null && bizMerchantReceiver1.getContractStatus().equals("2")) {
            return AjaxResult.error("已经签约过了，请勿重复提交");
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("name", bizMicroInfoByMerchId.getMerchIdcardName());//姓名
        data.put("idCard", bizMicroInfoByMerchId.getMerchIdcard());//身份证号
        data.put("cardNo", bizMicroInfoByMerchId.getMerchBankCardno());//银行卡号，
        data.put("mobile", bizMicroInfoByMerchId.getMerchBankMobile());//电话
        data.put("industry", "01");//职业
        data.put("phoneNo", bizMicroInfoByMerchId.getMerchBankMobile());//用户标识手机
        data.put("frontBase64", Base64Util.imageUrlToBase64(bizMicroInfoByMerchId.getMerchIdcardPositive()));//身份证正面
        data.put("backBase64", Base64Util.imageUrlToBase64(bizMicroInfoByMerchId.getMerchIdcardBack()));//背面
        data.put("remark", "01");//备注
        JSONObject jsonObject = HttpCallUtil.call(signingUrl, data, true);
        String retCode = jsonObject.getString("errCode");
        String ret_msg = jsonObject.getString("errMsg");

        if ("MBP0000".equals(retCode)) { //签约成功   //收款者表新增
            if (bizMerchantReceiver1 != null) {
                bizMerchantReceiver1.setContractStatus("2");
                iBizMerchantReceiverService.updateReceiver(bizMerchantReceiver1);
            } else {
                //查询出该商户
                BizMerchantReceiver receiver = new BizMerchantReceiver();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                String addTime = format.format(date);
                receiver.setMerchId(bizMerchantReceiver.getMerchId());
                receiver.setUserId(bizMerchantReceiver.getUserId());
                receiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
                receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
                receiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
                receiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());
                receiver.setMerchIdcardPositive(bizMicroInfoByMerchId.getMerchIdcardPositive());
                receiver.setContractStatus("2");
                receiver.setMerchIdcardBack(bizMicroInfoByMerchId.getMerchIdcardBack());
                receiver.setCreateTime(addTime);
                //先新增一条商户下发收款者
                iBizMerchantReceiverService.save(receiver);
            }
            ajaxResult.put("err_msg", ret_msg);
            System.out.println("-----------------" + ret_msg);
            //调取
            return AjaxResult.success("签约成功");
        } else if ("MBP0001".equals(retCode)) {
            if (bizMerchantReceiver1 == null) {
                //查询出该商户
                BizMerchantReceiver receiver = new BizMerchantReceiver();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                String addTime = format.format(date);
                receiver.setMerchId(bizMerchantReceiver.getMerchId());
                receiver.setUserId(bizMerchantReceiver.getUserId());
                receiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
                receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
                receiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
                receiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());
                receiver.setMerchIdcardPositive(bizMicroInfoByMerchId.getMerchIdcardPositive());
                receiver.setContractStatus("2");
                receiver.setMerchIdcardBack(bizMicroInfoByMerchId.getMerchIdcardBack());
                receiver.setCreateTime(addTime);
                //新增一条商户下发收款者
                iBizMerchantReceiverService.save(receiver);
            } else {
                bizMerchantReceiver1.setContractStatus("2");
                bizMerchantReceiver1.setErroMessage(ret_msg);
                iBizMerchantReceiverService.updateReceiver(bizMerchantReceiver1);
            }
            return AjaxResult.success("签约成功");
        } else {
            if (bizMerchantReceiver1 != null) {
                bizMerchantReceiver1.setContractStatus("3");
                bizMerchantReceiver1.setErroMessage(ret_msg);
                iBizMerchantReceiverService.updateReceiver(bizMerchantReceiver1);
            } else {
                BizMerchantReceiver receiver = new BizMerchantReceiver();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                String addTime = format.format(date);
                receiver.setMerchId(bizMerchantReceiver.getMerchId());
                receiver.setUserId(bizMerchantReceiver.getUserId());
                receiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
                receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
                receiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
                receiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());
                receiver.setMerchIdcardPositive(bizMicroInfoByMerchId.getMerchIdcardPositive());
                receiver.setContractStatus("3");
                receiver.setMerchIdcardBack(bizMicroInfoByMerchId.getMerchIdcardBack());
                receiver.setCreateTime(addTime);
                receiver.setErroMessage(ret_msg);
                //先新增一条商户下发收款者
                iBizMerchantReceiverService.save(receiver);
            }
            return AjaxResult.error(ret_msg);
        }
    }

    @ApiOperation("查询签约状态")
    @PostMapping("/echoReceiver")
    @Transactional
    public AjaxResult echoReceiver(@RequestBody BizMerchant bizMerchant) {
        AjaxResult ajaxResult = AjaxResult.success("查询商户是否签约");
        BizMerchantReceiver bizMerchantReceiver = bizMerchantService.selectBizMerchantReceiver(bizMerchant);
        if (bizMerchantReceiver == null) {
            ajaxResult.put("data", "0");
            ajaxResult.put("ret_msg", "商户待签约");
            return ajaxResult;
        }
        if (bizMerchantReceiver.getContractStatus().equals("0")) {
            ajaxResult.put("data", "0");
            ajaxResult.put("ret_msg", "商户待签约");
            return ajaxResult;
        } else if (bizMerchantReceiver.getContractStatus().equals("1")) {
            ajaxResult.put("data", "1");
            ajaxResult.put("ret_msg", "商户签约中");
            return ajaxResult;
        } else if (bizMerchantReceiver.getContractStatus().equals("3")) {
            ajaxResult.put("data", "3");
            ajaxResult.put("ret_msg", "商户签约失败");
            return ajaxResult;
        } else if (bizMerchantReceiver.getContractStatus().equals("4")) {
            ajaxResult.put("data", "4");
            ajaxResult.put("ret_msg", "商户拒签");
            return ajaxResult;
        } else {
            if (bizMerchantReceiver.getMerchId() == null || bizMerchantReceiver.getUserId() == null) {
                BizMerchantReceiver bizMerchantReceiver1 = new BizMerchantReceiver();
                bizMerchantReceiver1.setMerchId(bizMerchantReceiver.getMMerchId());
                bizMerchantReceiver1.setUserId(bizMerchantReceiver.getMUserId());
                bizMerchantReceiver1.setMerchIdcard(bizMerchantReceiver.getMerchIdcard());
                iBizMerchantReceiverService.updateReceiver(bizMerchantReceiver1);
            }
            ajaxResult.put("data", "2");
            ajaxResult.put("ret_msg", "商户已签约");
            return ajaxResult;
        }
    }

    @ApiOperation("安易发点击提现")
    @PostMapping("/clickWithdraw")
    @Transactional
    public AjaxResult clickWithdraw(@RequestBody BizWithdrawalRecords bizWithdrawalRecords) {
        AjaxResult ajaxResult = new AjaxResult();
        HashMap<String, Object> data = new HashMap<String, Object>();
        // 查询提现信息
        BizWithdrawalRecords byId = iBizWithdrawalRecordsService.getById(bizWithdrawalRecords.getId());
        BigDecimal arrivalAmount = byId.getArrivalAmount();
        String recvCustName = byId.getWithdrawalName();//收款者姓名
        BizMerchant merchantByUserId = bizMerchantService.getMerchantByUserId(byId.getUserId());
        BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(merchantByUserId.getMerchId());
        String recvCardNo = byId.getWithdrawalAccount();//收款者银行卡号
        // 订单编号
//        SysUser user = iSysUserService.selectUserById(bizWithdrawalRecords.getUserId());
        String str = "安心付闯业";
//        if(user.getDeptId() == 101L){
//            str = "安心付伙伴";
//        }else  if (user.getDeptId() == 102L){
//            str = "安心付乐富";
//        }
        String orderNo = str + OrderUtil.randomOrderNo();
        System.out.println("cust_1  :  " + orderNo);
        data.put("batchNo", orderNo);
        data.put("name",recvCustName );
        data.put("cardNo", recvCardNo);
        data.put("amount", arrivalAmount);
        data.put("idCard", bizMicroInfoByMerchId.getMerchIdcard());
        data.put("mobile", bizMicroInfoByMerchId.getMerchBankMobile());
        data.put("bgUrl", callbackUrl); // todo 回调地址要换
        data.put("remark", byId.getRemark()); // 备注  是谁家的 安心付-闯业  安心付-伙伴 安心付-乐富
        JSONObject jsonObject = HttpCallUtil.call(disbursementUrl, data,true);
        String retCode = jsonObject.getString("errCode");
        String ret_msg = jsonObject.getString("errMsg");
        if (retCode.equals("MBP0000")||retCode.equals("MBP0001")) {//成功
            byId.setOrderNo(orderNo);
            byId.setPayStatus("3");//进行中
            iBizWithdrawalRecordsService.saveOrUpdate(byId);
            System.out.println(ret_msg);
            ajaxResult = AjaxResult.success("支付成功，请关注回调接口。");
            ajaxResult.put("data", true);
            return ajaxResult;
        } else {
            //  输入参数引起的下单失败，可以直接把订单置为失败；
            byId.setPayStatus("0");//未发起
            iBizWithdrawalRecordsService.saveOrUpdate(byId);
            System.out.println(ret_msg);
            ajaxResult = AjaxResult.success(ret_msg+"支付失败。");
            ajaxResult.put("data", false);
            return ajaxResult;
        }
    }

    @ApiOperation(value = "安易发出款接口回调")
    @RequestMapping("/appli/callback")
    @Transactional
    public ApiBaseResult payCallBacks(@RequestBody ApiayfParam param) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = df.format(new Date());
        System.out.println("-------------------------------" + strDate + "---------------------------------------");
        System.out.println("------------------------------***接口回调支付接口回调***----------------------------");
        System.out.println("-------------------------------------------------------------------------------------");
        System.out.println("进入回调服务.");
        ApiBaseResult result = new ApiBaseResult();
        result.setRspCode("0000");
        result.setRspMsg("SUCCESS");
        System.out.println("------------------------回调接收参数---------------------------");
        System.out.println(JSON.toJSONString(param));
        System.out.println("------------------------回调返回参数---------------------------");
        System.out.println(JSON.toJSONString(result));
        // 获得提现记录 通过orderNo
        LambdaQueryWrapper<BizWithdrawalRecords> lambdaQueryWrapper =  Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(BizWithdrawalRecords::getOrderNo,param.getBatchNo());
        BizWithdrawalRecords one = iBizWithdrawalRecordsService.getOne(lambdaQueryWrapper);
        if (param.getStatusCode().equals("2")) { // 成功
            one.setPayStatus("1");//成功
            iBizWithdrawalRecordsService.saveOrUpdate(one);
            // todo 调取提现分润
            bizWithdrawalRecordsServiceImpl.executeMerchantWallet(one);
        }else {
            // 什么都不做
            one.setPayStatus("0");//未发起
            iBizWithdrawalRecordsService.saveOrUpdate(one);
            String message = param.getErrorMsg();
            System.out.println("------------------------支付失败----------------------------");
            System.out.println("通用支付异常");
            System.out.println(param.getBatchNo()+"--------------失败原因：" + param.getErrorMsg() + "------------------------"+message);
        }
        return result;
    }


}


